package com.vivz.baby.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.vivz.baby.common.Constants;
import com.vivz.baby.domain.Log;
import com.vivz.baby.repository.LogRepository;
import com.vivz.baby.util.CommonUtil;

@Component
public class LogDAO {

    @Autowired
    private LogRepository logRepository;

    public <S extends Log> S save(final S log) {
	return logRepository.save(log);
    }

    public void delete(final Log log) {
	logRepository.delete(log);
    }

    public <S extends Log> Iterable<S> save(final Collection<S> entities) {

	Collection<S> saved = new ArrayList<S>();
	for (Iterable<S> splitEntities : CommonUtil.split(entities, Constants.MAX_RECORDS)) {
	    Collection<S> save = (Collection<S>) logRepository.save(splitEntities);
	    System.out.println("Save collection of size [" + save.size() + "]");
	    saved.addAll(save);
	}

	return saved;
    }

    public Log findOne(final Long id) {
	return logRepository.findOne(id);
    }

    public boolean exists(final Long id) {
	return logRepository.exists(id);
    }

    public Iterable<Log> findByUserIdOrderByLogTimeDesc(Long userId) {
	return logRepository.findByUserIdOrderByLogTimeDesc(userId);
    }

    public Iterable<Log> findAll(final Iterable<Long> ids) {
	return logRepository.findAll(ids);
    }

    public long count() {
	return logRepository.count();
    }

    public void delete(final Long id) {
	logRepository.delete(id);
    }

    public void delete(final Iterable<? extends Log> entities) {
	logRepository.delete(entities);
    }

    public void deleteAll() {
	logRepository.deleteAll();
    }

    public List<Log> findByUserIdAndLogTimeBetween(Long userId, final Date d1, final Date d2) {
	final List<Log> logs = new ArrayList<Log>();
	if (d1 != null && d2 != null) {
	    final Date older = d1.before(d2) ? d1 : d2;
	    final Date newer = d1.before(d2) ? d2 : d1;

	    final List<Log> list = logRepository.findByUserIdAndLogTimeBetween(userId, older, newer);
	    if (CollectionUtils.isNotEmpty(list)) {
		logs.addAll(list);
	    }
	}
	return logs;
    }

}
